package com.ophiux.cs.application.consultBase.impl;

import com.ophiux.cs.application.consultBase.dto.AddDeptSortsRequest;
import com.ophiux.cs.application.consultBase.dto.AddDeptSortsResponse;
import com.ophiux.cs.application.consultBase.service.IAddDeptSortsAppService;
import com.ophiux.cs.application.core.AppResultCode;
import com.ophiux.cs.application.core.Result;
import com.ophiux.cs.application.core.ResultEnum;
import com.ophiux.cs.domain.consultBase.model.entity.DeptSorts;
import com.ophiux.cs.domain.consultBase.repositories.IDeptSortsRepository;
import com.ophiux.utils.common.RandomUtil;
import com.ophiux.utils.common.ShiftUtils;
import com.ophiux.utils.exception.OphiuxRepositoryException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class AddDeptSortsAppService implements IAddDeptSortsAppService {

    @Autowired
    IDeptSortsRepository deptSortsRepositories;


    @Override
    public Result<AddDeptSortsResponse> createDeptSorts(AddDeptSortsRequest dto) {
        AddDeptSortsResponse resp = new AddDeptSortsResponse();
        //验证参数是否允许为空
        if (!dto.isParamValid()) {
            return Result.fail(ResultEnum.requestParamFail.getCode(), ResultEnum.requestParamFail.getMsg());
        }
        try {
            DeptSorts deptSorts = null;
            deptSorts = (DeptSorts) ShiftUtils.objToNewObj(dto, DeptSorts.class);
            try {
                boolean flag=true;
                String dsID="";
                //生成科室分类编码
                while(flag){
                    //随机生成4位数
                    dsID= RandomUtil.getRandomNum(4);
                    DeptSorts ds=deptSortsRepositories.getDeptSortsByID(dsID);
                    if(ds==null){
                        deptSorts.setSORT_ID("S"+dsID);
                        flag=false;
                    }
                }
                deptSortsRepositories.createDeptSorts(deptSorts);
                resp.setSORT_ID(deptSorts.getSORT_ID());
            } catch (OphiuxRepositoryException e) {
                e.printStackTrace();
                return Result.fail(ResultEnum.requestException.getCode(), e.getExceptionMessage());
            }
        } catch (Exception e) {
            log.info("createDeptSorts接口异常：", e);
            e.printStackTrace();
            return Result.fail(AppResultCode.EXCEPTION, "程序异常");
        }
        return Result.success(resp, "新增科室分类成功");

    }
}
